package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.login.TsLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Operation(summary = "微信小程序登录")
    @GetMapping("wxLogin/{code}")
    public Result wxLogin(@PathVariable String code) {
        System.out.println("微信小程序登录，code：" + code);
        // 记录微信小程序登录的日志，使用占位符{}来防止日志注入
        log.info("微信小程序登录，code：{}", code);
        // 调用服务层的方法进行微信小程序的登录操作，返回包含用户信息的Map
        Map<String, Object> map = userInfoService.wxLogin(code);
        return Result.ok(map);
    }

    @TsLogin
    @Operation(summary = "微信小程序获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        Long userId = AuthContextHolder.getUserId();
        // 根据用户ID获取用户信息视图对象
        UserInfoVo userInfoVo = userInfoService.getUserInfo(userId);
        return Result.ok(userInfoVo);
    }

    @TsLogin
    @Operation(summary = "更新用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo) {
        //  从线程中获取当前用户ID
        Long userId = AuthContextHolder.getUserId();
        // 创建一个新的UserInfo对象以存储更新的用户信息
        UserInfo userInfo = new UserInfo();

        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());

        userInfoService.updateById(userInfo);
        return Result.ok(userInfo);
    }
}
